/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.plotnikov.pricemaker.patterns.observer;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.plotnikov.pricemaker.error.InitException;
import org.plotnikov.pricemaker.error.XMLException;
import org.plotnikov.pricemaker.utils.ComboIDs;
import org.plotnikov.pricemaker.xml.XMLDocumentBuilder;
import org.plotnikov.pricemaker.xml.XMLable;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 *
 * @author alexey
 */
public class PriceList implements PriceListInterface, XMLable, Cloneable{

    private Hashtable<String, DrawObject> figureHash = new Hashtable<String, DrawObject>();
    private JPanel panel;
    private Graphics priceGraph;
    private int width;
    private int height;
    private BufferedImage bimg;
    private Image image;
    /*
     * это поле только для сохранения ценника в БД при печати
     */
    private ComboIDs comboIDs = null;

    public PriceList(String imagepath) {
        panel = new PriceListPanel();
        MediaTracker mt = new MediaTracker(panel);
        image = Toolkit.getDefaultToolkit().createImage(imagepath);
        mt.addImage(image, 0);
        try {
            mt.waitForID(0);
        } catch (InterruptedException ie) {
        }
        width = image.getWidth(null);
        height = image.getHeight(null);
        bimg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        bimg.createGraphics().drawImage(image, 0, 0, panel);
        priceGraph = bimg.getGraphics();
    }

    public JPanel getPanel(){
        panel.removeAll();
        JLabel label = new JLabel(new ImageIcon(bimg));
        panel.add(label);

        panel.setMaximumSize(new Dimension(252, 189));
        panel.setMinimumSize(new Dimension(252, 189));
        panel.setSize(252, 189);
        return panel;
    }

    public void rebuildLayer(){
        bimg.createGraphics().drawImage(image, 0, 0, panel);
        
        priceGraph = bimg.getGraphics();
        Set<String> set = figureHash.keySet();
        for (Iterator<String> it = set.iterator(); it.hasNext();) {
            String key = it.next();
            DrawObject refreshobj = figureHash.get(key);
            priceGraph.setColor(Color.BLACK);
            priceGraph.setFont(new Font(refreshobj.getFontName(), refreshobj.getFontStyle(), refreshobj.getFontSize()));
            priceGraph.drawString(refreshobj.drawString(), refreshobj.getWidth(), refreshobj.getHeight());
        }
        panel.repaint();
    }

    public void addRefreshObjectToHash(DrawObject refreshobj){
        figureHash.put(refreshobj.getControlName(), refreshobj);
    }

    public void refreshLayer(DrawObject refreshobj) {
        figureHash.put(refreshobj.getControlName(), refreshobj);
        rebuildLayer();
    }

    public int getImageWidth(){
        return width;
    }

    public int getImageHeight(){
        return height;
    }

    public DrawObject getDrawObjFromHash(String key) {
        return figureHash.get(key);
    }

    public void setFigureHash(Hashtable<String, DrawObject> figureHash) {
        this.figureHash = figureHash;
    }

    public String makeXML() throws XMLException {
        XMLDocumentBuilder xml = new XMLDocumentBuilder();
        xml.getRootElement().setAttribute("width", ""+width);
        xml.getRootElement().setAttribute("height", ""+height);
        Set<String> set = figureHash.keySet();
        for (Iterator<String> it = set.iterator(); it.hasNext();) {
            String key = it.next();
            DrawObject drawobj = figureHash.get(key);
            Element root_2 = xml.createElement(key);
            root_2.setAttribute("width", ""+drawobj.getWidth());
            root_2.setAttribute("height", ""+drawobj.getHeight());
            root_2.setAttribute("draw", drawobj.getDrawString());
            root_2.setAttribute("fontsize", ""+drawobj.getFontSize());
            root_2.setAttribute("fontname", drawobj.getFontName());
            root_2.setAttribute("fontstyle", ""+drawobj.getFontStyle());

            xml.getRootElement().appendChild(root_2);

        }
        return xml.makeXML();
    }

    public void buildView(String s) throws InitException  {
        XMLDocumentBuilder xml = new XMLDocumentBuilder();
        if (!xml.loadXML(s))
            throw new InitException("Не удалось распознать координаты ценника.");
//        figureHash.clear();
        Element el = xml.getRootElement();
        NodeList nl = el.getChildNodes();
        for (int i = 0; i < nl.getLength(); i++) {
            Node n = nl.item(i);
            if (n.getNodeType()==Node.ELEMENT_NODE){
                figureHash.put(n.getNodeName(), readObject(n, n.getNodeName()));
            }
            
        }
        rebuildLayer();
    }

    private DrawObject readObject(Node n, final String name) throws InitException{
        Node n_width = n.getAttributes().getNamedItem("width");
        if (n_width==null)
            throw new InitException("Не удалось распознать координаты ценника(ошибочно сохранен).");

        Node n_height = n.getAttributes().getNamedItem("height");
        if (n_height==null)
            throw new InitException("Не удалось распознать координаты ценника(ошибочно сохранен).");

        Node n_draw = n.getAttributes().getNamedItem("draw");
        if (n_draw==null)
            throw new InitException("Не удалось распознать координаты ценника(ошибочно сохранен).");

        Node n_fontsize = n.getAttributes().getNamedItem("fontsize");
        if (n_fontsize==null)
            throw new InitException("Не удалось распознать координаты ценника(ошибочно сохранен).");

        Node n_fontname = n.getAttributes().getNamedItem("fontname");
        if (n_fontname==null)
            throw new InitException("Не удалось распознать координаты ценника(ошибочно сохранен).");

        Node n_fontstyle = n.getAttributes().getNamedItem("fontstyle");
        if (n_fontstyle==null)
            throw new InitException("Не удалось распознать координаты ценника(ошибочно сохранен).");

        try{
            return new DrawObject(new Integer(n_width.getNodeValue()),
                    new Integer(n_height.getNodeValue()),
                    n_draw.getNodeValue(),
                    new Integer(n_fontsize.getNodeValue()),
                    n_fontname.getNodeValue(),
                    new Integer(n_fontstyle.getNodeValue()),
                    name);
        }catch (NumberFormatException nfe){
            nfe.printStackTrace();
            throw new InitException("Не удалось распознать координаты ценника(ошибочно сохранен).");
        }
    }

    @Override
    public Object clone() {
        PriceList price = new PriceList(System.getProperty("user.dir") + java.io.File.separator + "pict.jpg");
        Hashtable<String, DrawObject> hash = new Hashtable<String, DrawObject>();

        Set<String> set = figureHash.keySet();
        for (Iterator<String> it = set.iterator(); it.hasNext();) {
            String key = it.next();
            DrawObject drawobj = figureHash.get(key);
            hash.put(key, new
                    DrawObject(drawobj.getWidth(), drawobj.getHeight(),
                    drawobj.getDrawString(), drawobj.getFontSize(),
                    drawobj.getFontName(), drawobj.getFontStyle(), drawobj.getControlName())
                    );
        }
        price.setFigureHash(hash);
        return price;
    }

    public void setNumPanel(int num) {
        PriceListPanel plp = null;
        if (panel instanceof PriceListPanel){
            plp = (PriceListPanel) panel;
            plp.setNum(num);
        }
    }

    public void setComboIDs(ComboIDs c) {
        this.comboIDs = c;
    }

    public ComboIDs getComboIDs() {
        return comboIDs;
    }

}
